<?php
namespace app\middleware;

use app\admin\constants\CacheConstants;
use app\model\AdminModel;
use Shopwwi\LaravelCache\Cache;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AdminAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next) : Response
    {
        //TODO 后台权限验证

        $controller = $request->controller;

        if($controller != 'app\admin\controller\PublicController'){
            //登陆权限验证

            $Authorization = $request->header('Authorization');

            if(!$Authorization){
                return error('请先登陆','',[],401);
            }

            $admin_id = Cache::tags(CacheConstants::TAG_LOGIN_TOKEN)->get('admin_token_'.$Authorization);

            if(!$admin_id){
                return error('请先登陆','',[],401);
            }

            $request->admin_id = $admin_id;
            $request->admin_token = $Authorization;

            $admininfo = get_admin_info($admin_id);

            if(!$admininfo || $admininfo['status'] != 1){
                return error('账号不存在或被禁用','',[],401);
            }

            $controller = $request->controller;
            $action = $request->action;
            $app = $request->app;
            
            //权限验证
            if(!AdminModel::canAccess($app,$controller,$action)){

                return error('没有访问权限');
            }

            

           

            


        }



        return $next($request);
    }
    
}
